/*
 * This file is part of the K-net login application.
 *
 * K-net login application is free software: you can redistribute it
 * and/or modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation, either version 3 of 
 * the License, or (at your option) any later version.
 *
 * K-net login is distributed in the hope that it will be useful, but 
 * WITHOUT ANY WARRANTY; without even the implied warranty of 
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License 
 * along with the K-net login application.
 * If not, see <http://www.gnu.org/licenses/>.
 */

/*
 * Copyright (C) 2011 Ulrik Andersen.
 * Copyright (C) 2011 Kasper Sjørslev.
 */

package dk.knet.login;

import android.util.Log;

import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;

public class Ping {
	
	private static final String TAG = "Ping";
	
	public boolean ping(String hostname) {
		boolean succes = false;
		
		try {
			InetAddress address = InetAddress.getByName( hostname );
			
			if(MainService.LOG) {
				Log.i(TAG, "Name: " + address.getHostName());
				Log.i(TAG, "Addr: " + address.getHostAddress());
			}
			
			boolean reachable = address.isReachable(3000);
			
			if(reachable) {
				if(MainService.LOG) Log.i(TAG, "Reach: " + reachable);
				succes = true;
			}
			else {
				if(MainService.LOG) Log.i(TAG, "Reach: " + reachable);
				succes = false;
			}
		}
		catch (UnknownHostException e) {
			if(MainService.LOG) Log.e(TAG, "Unable to lookup " + hostname);
			succes = false;
		}
		catch (IOException e) {
			if(MainService.LOG) Log.e(TAG, "Unable to reach " + hostname);
			succes = false;
		}
		return succes;
	}
}
